package com.hd.vue2204.fm.controller;

import com.hd.vue2204.fm.entity.User;
import com.hd.vue2204.fm.service.UserService;
import com.hd.vue2204.fm.vo.UserRisterVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户  前端控制器
 * </p>
 *
 * @author hd
 * @since 2023-04-19
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UsersController {
    @Autowired
    UserService userService;

    @PostMapping("/regist")
    public Map<String,Object> regist(@RequestBody UserRisterVo userRisterVo){
        HashMap<String, Object> map = new HashMap<>();

        boolean flag = userService.regist(userRisterVo.getUsername(), userRisterVo.getPassword());

        if (flag){
            map.put("code",10000);
        }else {
            map.put("code",-1);
        }

        return map;
    }

    @GetMapping("/login")
    public Map<String,Object> login(String username,String password){
        HashMap<String, Object> map = new HashMap<>();

        //1.使用 shiro提供的 api 进行用户登录操作

        // 1.1 获取shiro的核心对象 Subject， 该对象代表当前用户
        Subject subject = SecurityUtils.getSubject();

        //1.2准备参数UsernamePasswordToken 对象
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);

        //1.3使用shiro的登录方法完成登录过程
        subject.login(usernamePasswordToken);

        User user = (User) subject.getPrincipal();

        if (user!=null){
            map.put("code",10000);
            Map<String,Object> map1 = new HashMap<>();
            /*map1.put("userId",user.getUserId());
            map1.put("username",user.getUsername());
            map1.put("userImg",user.getUserImg());*/
            map.put("data",user);

        }else {
            map.put("code",-1);
        }

        return map;
    }

}
